package editor.logic;

import moltencore.game.loader.Level;
import moltencore.game.loader.LevelSprite;
import spark.graphics.SpriteMap;
import spark.graphics.SpriteRenderable;
import spark.graphics.ISpriteMap;
import spark.graphics.Sprite;
import spark.exception.LoadingException;
import spark.math.Vector3;
import spark.math.Vector2;

import java.util.HashMap;

import editor.graphics.LevelSpriteFactoryHandler;
import editor.graphics.Window;
import blazingbubble.config.Config;

public class LevelSpriteFactory {
	public static LevelSpriteFactoryHandler levelSpriteFactoryHandler;
	private String spriteMapName;
	private String themePath;
	private String theme;
	private HashMap<String, SpriteMap.SpriteData> spriteDataMap;
	private ISpriteMap spriteMap = null;

	public LevelSpriteFactory(String spriteMapName, String themePath, String theme, HashMap<String, SpriteMap.SpriteData> spriteDataMap) throws LoadingException {
		this.spriteMapName = spriteMapName;
		this.themePath = themePath;
		if(levelSpriteFactoryHandler.containsFactory(getIdent())) {
			throw new LoadingException("Factory alraedy created");
		}
		this.theme = theme;
		this.spriteDataMap = spriteDataMap;
		if(levelSpriteFactoryHandler != null) {
			levelSpriteFactoryHandler.levelSpriteFactoryCreated(this);
		}
	}

	public LevelSprite getLevelSprite(String id) throws LoadingException {
		SpriteRenderable spriteRenderable = new SpriteRenderable();
		Vector2 spriteDimensions = new Vector2(spriteDataMap.get(id).dimensions);
		spriteDimensions.divide(Level.UNIT_PIXEL_RATIO);
		Vector2 spriteLeftTop = new Vector2(spriteDimensions);
		spriteLeftTop.divide(2.0f);
		spriteLeftTop.x *= -1;
		spriteRenderable.setPosition(new Vector3());
		spriteRenderable.setDimensions(spriteDimensions);
		spriteRenderable.setSprite(getSprite(id));
		return new LevelSprite(spriteRenderable, spriteMapName, theme, id);
	}

	private Sprite getSprite(String id) throws LoadingException {
		return getSpriteMap().getSprite(id);
	}

	public String getIdent() {
		return spriteMapName + ":" + theme;
	}

	public String getSpriteName() {
		return spriteMapName;
	}

	public String getThemePath() {
		return themePath;
	}

	public String getTheme() {
		return theme;
	}

	public HashMap<String, SpriteMap.SpriteData> getSpriteDataMap() {
		return spriteDataMap;
	}

	public ISpriteMap getSpriteMap() throws LoadingException {
		if(spriteMap == null) {
			String mapPath = "";
			if(!spriteMapName.contains(Config.getResourcePath().substring(2))) {
				mapPath = Config.getResourcePath() + Window.SPRITE_MAP_PATH + "/";
			}
			spriteMap = new SpriteMap(mapPath + spriteMapName, theme, themePath);
		}
		return spriteMap;
	}
}
